package top.ninwoo.edgecenter.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import top.ninwoo.edgecenter.service.IpService;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author joliu
 * @Description
 * @Date　Create in 下午8:20 2019/11/7
 */
@Service
public class IpServiceImpl implements IpService {

    private static final Logger LOG = LoggerFactory.getLogger(IpServiceImpl.class);
    // clusterId, String appName, String cid, String ipRange
    private static final String ASSIGN_IP = "/assignIp?clusterId={clusterId}&appName={appName}&cid={cid}&ipRange={ipRange}";
    private static final String GET_IP_BY_CONTAINERID = "/getIpByContainerId?cid=";
    private static final String DELETE_IP = "/deleteIp?clusterId={clusterId}&appName={appName}&containerId={containerId}&ip={ip}";

    @Value("${bs.ipservice.ip}")
    private String ipServiceHost;

    @Autowired
    RestTemplate restTemplate;


    ConcurrentHashMap<String, AtomicInteger> countMap = new ConcurrentHashMap<>();
    ConcurrentHashMap<String, String> ipMap = new ConcurrentHashMap<>();


    // TODO: 这个应该结合数据库，由云端提供服务，暂时提供一个测试版本
    @Override
    public String assignIpString(long clusterId, String appName, String containerId, String networkSegment) {
        Map<String, Object> map = new HashMap<>();
        map.put("clusterId", clusterId);
        map.put("appName", appName);
        map.put("cid", containerId);
        map.put("ipRange", networkSegment);
        ResponseEntity<String> forEntity = restTemplate.getForEntity("http://" + ipServiceHost + ASSIGN_IP, String.class, map);
        if (!forEntity.getStatusCode().is2xxSuccessful()) {
            throw new RuntimeException("获取ip失败" + forEntity.getBody());
        }
        return forEntity.getBody();
    }

    @Override
    public String deleteIP(long clusterId, String appName, String containerId, String ip) {
        Map<String, Object> param = new HashMap<>();
        param.put("clusterId", clusterId);
        param.put("appName", appName);
        param.put("containerId", containerId);
        param.put("ip", ip);
        return restTemplate.getForObject("http://" + ipServiceHost + DELETE_IP, String.class, param);
    }
    @Override
    public String getContainerIp(String containerId) {
        // 更换为远程接口
        String ip = restTemplate.getForObject("http://" + ipServiceHost + GET_IP_BY_CONTAINERID + containerId, String.class);
        if("".equals(ip)) {
            LOG.warn("容器 {} 没有查询到已分配的ip", containerId);
        }
        return ip;
    }
}
